package com.zjj.shiro.authentication;

import java.security.Principal;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.util.Factory;
import org.junit.Test;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

public class AuthentictorTest {

	/**
	 * AllSuccessfulStrategy
	 * 所有Realm验证成功才算成功，且返回所有Realm身份验证成功的认证信息，如果有一个失败就失败了
	 */
	@Test
	public void testAllSuccess() {
		login("classpath:shiro-all-authenticator-success.ini");
		
		Subject subject = SecurityUtils.getSubject();
		PrincipalCollection principalCollection = subject.getPrincipals();
		System.out.println("成功数量：" + principalCollection.asList().size());
	}
	
	@Test
	public void testAllFail() {
		login("classpath:shiro-all-authenticator-fail.ini");
		
		Subject subject = SecurityUtils.getSubject();
		PrincipalCollection principalCollection = subject.getPrincipals();
		System.out.println("成功数量：" + principalCollection.asList().size());
	}

	/**
	 * FirstSuccessfulStrategy
	 * 只要有一个Realm验证成功即可，只返回第一个Realm身份验证成功的认证信息，其他的忽略；
	 */
	@Test
	public void testFirstSuccess() {
		login("classpath:shiro-all-authenticator-success.ini");
		
		Subject subject = SecurityUtils.getSubject();
		PrincipalCollection principalCollection = subject.getPrincipals();
		System.out.println("成功数量：" + principalCollection.asList().size());
	}
	
	/**
	 * AtLeastOneSuccessfulStrategy
	 * 只要有一个Realm验证成功即可，和FirstSuccessfulStrategy不同，返回所有Realm身份验证成功的认证信息；
	 */
	@Test
	public void testAtLeastOneSuccess() {
		login("classpath:shiro-all-authenticator-atLeastOne-success.ini");
		
		Subject subject = SecurityUtils.getSubject();
		PrincipalCollection principalCollection = subject.getPrincipals();
		System.out.println("成功数量：" + principalCollection.asList().size());
	}
	
	/**
	 * 自定义AuthenticationStrategy实现
	 */
	@Test
	public void testAtLeastTwoStrategyWithSuccess() {
		login("classpath:shiro-all-authenticator-atLeastTwo-success.ini");
		
		Subject subject = SecurityUtils.getSubject();
		PrincipalCollection principalCollection = subject.getPrincipals();
		// 因为myRealm1和myRealm4返回的身份一样所以输出时只返回一个
		System.out.println("成功数量：" + principalCollection.asList().size());
	}
	
	
	
	private void login(String config) {
		Factory<SecurityManager> factory = new IniSecurityManagerFactory(config);
		
		SecurityManager securityManager = factory.getInstance();
		SecurityUtils.setSecurityManager(securityManager);
		
		Subject subject = SecurityUtils.getSubject();
		
		UsernamePasswordToken token = new UsernamePasswordToken("zjj", "123");
		subject.login(token);
	}
}
